/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.desktop.ui.util.comparator;

import java.util.Comparator;

/**
 * @author Oleg Anastassov
 */
public class StringComparator<T> implements Comparator<T> {
    private int columnIndex = -1;
    private short ascending = 1;

    /**
     * Constructor with columns amount parameter.
     *
     * @param column column amount.
     */
    public StringComparator(int column) {
        super();
        this.columnIndex = column;
    }

    /**
     * Constructor with columns amount and sort mode parameters.
     *
     * @param column    columns count.
     * @param ascending if true sort mode would be ASC, otherwise DESC.
     */
    public StringComparator(int column, boolean ascending) {
        this(column);
        if (!ascending) {
            this.ascending = -1;
        }
    }

    /**
     * Compares value in rows by determinate column index.
     *
     * @param row1 first array of objects.
     * @param row2 second array of objects.
     * @return result of compare.
     */
    public int compare(T row1, T row2) {
        String value1 = null;
        String value2 = null;
        if (row1 instanceof Object[] && row2 instanceof Object[]) {
            Object o1 = ((Object[]) row1)[columnIndex];
            value1 = (o1 != null) ? o1.toString() : null;
            Object o2 = ((Object[]) row2)[columnIndex];
            value2 = (o2 != null) ? o2.toString() : null;
        }

        if (value1 != null) {
            if (value2 != null) {
                return value1.compareToIgnoreCase(value2) * ascending;
            } else {
                return ascending;
            }
        } else {
            if (value2 != null) {
                return -ascending;
            } else {
                return 0;
            }
        }
    }
}
